import 'dart:convert';
import 'dart:math';
import '../models/course.dart';

/// 课程服务类
class CourseService {
  static final CourseService _instance = CourseService._internal();
  factory CourseService() => _instance;
  CourseService._internal();
  
  static CourseService get instance => _instance;

  // 模拟数据存储
  final List<Course> _courses = [];
  final List<String> _userEnrollments = []; // 用户报名记录
  final List<String> _userFavorites = []; // 用户收藏记录
  final Map<String, double> _userProgress = {}; // 用户学习进度
  final List<Instructor> _instructors = [];

  /// 初始化模拟数据
  void initializeMockData() {
    if (_courses.isNotEmpty) return;

    final now = DateTime.now();
    
    // 初始化讲师数据
    _instructors.addAll([
      Instructor(
        id: '1',
        name: '李传承',
        title: '国家级非遗传承人',
        avatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=elderly%20Chinese%20master%20craftsman%20portrait&image_size=square',
        bio: '从事传统手工艺30余年，精通多种传统技艺，致力于非遗文化的传承与发展。',
        expertise: ['传统手工艺', '非遗文化', '技艺传承'],
        rating: 4.9,
        studentCount: 1250,
      ),
      Instructor(
        id: '2',
        name: '王文化',
        title: '民俗学教授',
        avatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=Chinese%20professor%20in%20traditional%20clothing&image_size=square',
        bio: '北京大学民俗学教授，专注于中国传统文化研究与教育。',
        expertise: ['民俗学', '传统文化', '历史研究'],
        rating: 4.8,
        studentCount: 890,
      ),
      Instructor(
        id: '3',
        name: '张艺术',
        title: '工艺美术大师',
        avatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=Chinese%20art%20master%20in%20workshop&image_size=square',
        bio: '中国工艺美术大师，擅长传统雕刻和绘画技艺。',
        expertise: ['雕刻艺术', '传统绘画', '工艺美术'],
        rating: 4.7,
        studentCount: 650,
      ),
    ]);

    // 初始化课程数据
    _courses.addAll([
      Course(
        id: '1',
        title: '传统剪纸艺术入门',
        description: '学习中国传统剪纸艺术的基本技法，从简单的花鸟图案开始，逐步掌握复杂的剪纸技巧。课程包含理论讲解和实践操作，让学员在动手中感受传统文化的魅力。',
        instructor: _instructors[0],
        type: CourseType.basic,
        difficulty: CourseDifficulty.beginner,
        status: CourseStatus.upcoming,
        startDate: now.add(const Duration(days: 7)),
        endDate: now.add(const Duration(days: 37)),
        duration: 30, // 30天
        price: 299.0,
        originalPrice: 399.0,
        maxStudents: 50,
        currentStudents: 32,
        chapters: [
          CourseChapter(
            id: '1-1',
            title: '剪纸艺术概述',
            description: '了解剪纸艺术的历史渊源和文化内涵',
            duration: 45,
            videoUrl: 'https://example.com/video/1-1',
            materials: ['剪纸历史资料.pdf', '基础工具介绍.ppt'],
            isCompleted: false,
            order: 1,
          ),
          CourseChapter(
            id: '1-2',
            title: '基础工具与材料',
            description: '认识剪纸所需的工具和材料',
            duration: 30,
            videoUrl: 'https://example.com/video/1-2',
            materials: ['工具清单.pdf'],
            isCompleted: false,
            order: 2,
          ),
          CourseChapter(
            id: '1-3',
            title: '简单花卉剪纸',
            description: '学习剪制简单的花卉图案',
            duration: 60,
            videoUrl: 'https://example.com/video/1-3',
            materials: ['花卉图案模板.pdf', '剪纸步骤图.jpg'],
            isCompleted: false,
            order: 3,
          ),
        ],
        requirements: ['无需基础', '准备剪刀和彩纸'],
        outcomes: ['掌握基本剪纸技法', '能够独立完成简单作品', '了解剪纸文化内涵'],
        hasCertificate: true,
        language: '中文',
        createdAt: now.subtract(const Duration(days: 30)),
        updatedAt: now.subtract(const Duration(hours: 2)),
        isFeatured: true,
        rating: 4.8,
        reviewCount: 156,
        tags: ['剪纸', '传统艺术', '手工制作', '入门课程'],
      ),
      Course(
        id: '2',
        title: '中国书法基础教程',
        description: '从零开始学习中国书法，掌握正确的执笔姿势、基本笔画和字体结构。通过系统的练习，培养书法审美能力和文化素养。',
        instructor: _instructors[1],
        type: CourseType.advanced,
        difficulty: CourseDifficulty.beginner,
        status: CourseStatus.ongoing,
        startDate: now.subtract(const Duration(days: 10)),
        endDate: now.add(const Duration(days: 50)),
        duration: 60, // 60天
        price: 499.0,
        originalPrice: 699.0,
        maxStudents: 30,
        currentStudents: 28,
        chapters: [
          CourseChapter(
            id: '2-1',
            title: '书法概论',
            description: '了解书法的历史发展和艺术特点',
            duration: 50,
            videoUrl: 'https://example.com/video/2-1',
            materials: ['书法史简介.pdf'],
            isCompleted: false,
            order: 1,
          ),
          CourseChapter(
            id: '2-2',
            title: '执笔与坐姿',
            description: '学习正确的执笔方法和书写姿势',
            duration: 40,
            videoUrl: 'https://example.com/video/2-2',
            materials: ['执笔要领.pdf', '坐姿示范.jpg'],
            isCompleted: false,
            order: 2,
          )
        ],
        requirements: ['无需基础', '准备毛笔、墨汁、宣纸'],
        outcomes: ['掌握基本笔画', '能写简单汉字', '培养书法兴趣'],
        hasCertificate: true,
        language: '中文',
        createdAt: now.subtract(const Duration(days: 25)),
        updatedAt: now.subtract(const Duration(hours: 1)),
        isFeatured: true,
        rating: 4.9,
        reviewCount: 203,
        tags: ['书法', '传统文化', '艺术修养', '基础教程'],
      ),
      Course(
        id: '3',
        title: '传统茶艺文化课',
        description: '深入了解中国茶文化，学习茶叶知识、泡茶技艺和茶道礼仪。通过理论学习和实践操作，感受茶文化的深厚底蕴。',
        instructor: _instructors[2],
        type: CourseType.workshop,
        difficulty: CourseDifficulty.intermediate,
        status: CourseStatus.upcoming,
        startDate: now.add(const Duration(days: 20)),
        endDate: now.add(const Duration(days: 65)),
        duration: 45, // 45天
        price: 399.0,
        originalPrice: 599.0,
        maxStudents: 25,
        currentStudents: 0,
        chapters: [
          CourseChapter(
            id: '3-1',
            title: '茶文化概述',
            description: '了解中国茶文化的历史和发展',
            duration: 60,
            videoUrl: 'https://example.com/video/3-1',
            materials: ['茶文化史.pdf'],
            isCompleted: false,
            order: 1,
          )
        ],
        requirements: ['对茶文化有兴趣', '准备茶具'],
        outcomes: ['了解茶文化历史', '掌握泡茶技艺', '学会茶道礼仪'],
        hasCertificate: true,
        language: '中文',
        createdAt: now.subtract(const Duration(days: 15)),
        updatedAt: now.subtract(const Duration(hours: 4)),
        isFeatured: false,
        rating: 4.6,
        reviewCount: 45,
        tags: ['茶艺', '传统文化', '礼仪', '中级课程'],
      ),
    ]);
  }

  /// 获取所有课程
  Future<List<Course>> getAllCourses() async {
    await Future.delayed(const Duration(milliseconds: 500));
    return List.from(_courses);
  }

  /// 筛选课程
  List<Course> filterCourses(List<Course> courses, CourseFilter filter) {
    switch (filter) {
      case CourseFilter.all:
        return courses;
      case CourseFilter.upcoming:
        return courses.where((c) => c.status == CourseStatus.upcoming).toList();
      case CourseFilter.ongoing:
        return courses.where((c) => c.status == CourseStatus.ongoing).toList();
      case CourseFilter.completed:
        return courses.where((c) => c.status == CourseStatus.completed).toList();
      case CourseFilter.basic:
        return courses.where((c) => c.type == CourseType.basic).toList();
      case CourseFilter.advanced:
        return courses.where((c) => c.type == CourseType.advanced).toList();
      case CourseFilter.master:
        return courses.where((c) => c.type == CourseType.master).toList();
      case CourseFilter.workshop:
        return courses.where((c) => c.type == CourseType.workshop).toList();
      case CourseFilter.online:
        return courses.where((c) => c.type == CourseType.online).toList();
      case CourseFilter.offline:
        return courses.where((c) => c.type == CourseType.offline).toList();
      case CourseFilter.featured:
        return courses.where((c) => c.isFeatured).toList();
      case CourseFilter.free:
        return courses.where((c) => c.price == 0).toList();
      case CourseFilter.paid:
        return courses.where((c) => c.price > 0).toList();
    }
  }

  /// 根据筛选条件获取课程
  Future<List<Course>> getCoursesByFilter(CourseFilter filter) async {
    await Future.delayed(const Duration(milliseconds: 300));
    
    switch (filter) {
      case CourseFilter.all:
        return List.from(_courses);
      case CourseFilter.upcoming:
        return _courses.where((c) => c.status == CourseStatus.upcoming).toList();
      case CourseFilter.ongoing:
        return _courses.where((c) => c.status == CourseStatus.ongoing).toList();
      case CourseFilter.completed:
        return _courses.where((c) => c.status == CourseStatus.completed).toList();
      case CourseFilter.basic:
        return _courses.where((c) => c.type == CourseType.basic).toList();
      case CourseFilter.advanced:
        return _courses.where((c) => c.type == CourseType.advanced).toList();
      case CourseFilter.master:
        return _courses.where((c) => c.type == CourseType.master).toList();
      case CourseFilter.workshop:
        return _courses.where((c) => c.type == CourseType.workshop).toList();
      case CourseFilter.online:
        return _courses.where((c) => c.type == CourseType.online).toList();
      case CourseFilter.offline:
        return _courses.where((c) => c.type == CourseType.offline).toList();
      case CourseFilter.featured:
        return _courses.where((c) => c.isFeatured).toList();
      case CourseFilter.free:
        return _courses.where((c) => c.price == 0).toList();
      case CourseFilter.paid:
        return _courses.where((c) => c.price > 0).toList();
    }
  }

  /// 获取热门课程
  Future<List<Course>> getHotCourses({int limit = 5}) async {
    await Future.delayed(const Duration(milliseconds: 300));
    final hotCourses = List.from(_courses)
      ..sort((a, b) => (b.rating * b.reviewCount).compareTo(a.rating * a.reviewCount));
    return hotCourses.take(limit).toList().cast<Course>();
  }

  /// 获取推荐课程
  Future<List<Course>> getRecommendedCourses({int limit = 5}) async {
    await Future.delayed(const Duration(milliseconds: 300));
    final recommended = _courses.where((c) => 
      c.status == CourseStatus.upcoming || c.status == CourseStatus.ongoing
    ).toList()
      ..shuffle(Random());
    return recommended.take(limit).toList();
  }

  /// 获取精选课程
  Future<List<Course>> getFeaturedCourses({int limit = 3}) async {
    await Future.delayed(const Duration(milliseconds: 300));
    return _courses.where((c) => c.isFeatured).take(limit).toList();
  }

  /// 根据ID获取课程详情
  Future<Course?> getCourseById(String id) async {
    await Future.delayed(const Duration(milliseconds: 200));
    try {
      return _courses.firstWhere((c) => c.id == id);
    } catch (e) {
      return null;
    }
  }

  /// 搜索课程
  Future<List<Course>> searchCourses(String query) async {
    await Future.delayed(const Duration(milliseconds: 400));
    if (query.isEmpty) return [];
    
    final lowerQuery = query.toLowerCase();
    return _courses.where((course) {
      return course.title.toLowerCase().contains(lowerQuery) ||
             course.description.toLowerCase().contains(lowerQuery) ||
             course.tags.any((tag) => tag.toLowerCase().contains(lowerQuery)) ||
             course.instructor.name.toLowerCase().contains(lowerQuery);
    }).toList();
  }

  /// 报名课程
  Future<bool> enrollCourse(String courseId, String userId) async {
    await Future.delayed(const Duration(milliseconds: 500));
    
    final course = await getCourseById(courseId);
    if (course == null || !course.canEnroll) {
      return false;
    }

    final enrollmentKey = '${userId}_$courseId';
    if (_userEnrollments.contains(enrollmentKey)) {
      return false; // 已经报名
    }

    // 更新课程报名人数
    final index = _courses.indexWhere((c) => c.id == courseId);
    if (index != -1) {
      _courses[index] = _courses[index].copyWith(
        currentStudents: _courses[index].currentStudents + 1,
      );
      _userEnrollments.add(enrollmentKey);
      _userProgress[enrollmentKey] = 0.0; // 初始化学习进度
      return true;
    }
    
    return false;
  }

  /// 取消报名
  Future<bool> unenrollCourse(String courseId, String userId) async {
    await Future.delayed(const Duration(milliseconds: 300));
    
    final enrollmentKey = '${userId}_$courseId';
    if (!_userEnrollments.contains(enrollmentKey)) {
      return false; // 未报名
    }

    // 更新课程报名人数
    final index = _courses.indexWhere((c) => c.id == courseId);
    if (index != -1) {
      _courses[index] = _courses[index].copyWith(
        currentStudents: _courses[index].currentStudents - 1,
      );
      _userEnrollments.remove(enrollmentKey);
      _userProgress.remove(enrollmentKey);
      return true;
    }
    
    return false;
  }

  /// 检查用户是否已报名
  Future<bool> isUserEnrolled(String courseId, String userId) async {
    await Future.delayed(const Duration(milliseconds: 100));
    final enrollmentKey = '${userId}_$courseId';
    return _userEnrollments.contains(enrollmentKey);
  }

  /// 更新学习进度
  Future<bool> updateProgress(String courseId, String userId, double progress) async {
    await Future.delayed(const Duration(milliseconds: 200));
    final enrollmentKey = '${userId}_$courseId';
    if (_userEnrollments.contains(enrollmentKey)) {
      _userProgress[enrollmentKey] = progress.clamp(0.0, 1.0);
      return true;
    }
    return false;
  }

  /// 获取学习进度
  Future<double> getProgress(String courseId, String userId) async {
    await Future.delayed(const Duration(milliseconds: 100));
    final enrollmentKey = '${userId}_$courseId';
    return _userProgress[enrollmentKey] ?? 0.0;
  }

  /// 收藏课程
  Future<bool> favoriteCourse(String courseId, String userId) async {
    await Future.delayed(const Duration(milliseconds: 200));
    final favoriteKey = '${userId}_$courseId';
    if (!_userFavorites.contains(favoriteKey)) {
      _userFavorites.add(favoriteKey);
      return true;
    }
    return false;
  }

  /// 取消收藏
  Future<bool> unfavoriteCourse(String courseId, String userId) async {
    await Future.delayed(const Duration(milliseconds: 200));
    final favoriteKey = '${userId}_$courseId';
    return _userFavorites.remove(favoriteKey);
  }

  /// 检查用户是否已收藏
  Future<bool> isCourseFavorited(String courseId, String userId) async {
    await Future.delayed(const Duration(milliseconds: 100));
    final favoriteKey = '${userId}_$courseId';
    return _userFavorites.contains(favoriteKey);
  }

  /// 获取用户收藏的课程
  Future<List<Course>> getUserFavoriteCourses(String userId) async {
    await Future.delayed(const Duration(milliseconds: 300));
    final favoriteCourseIds = _userFavorites
        .where((key) => key.startsWith('${userId}_'))
        .map((key) => key.split('_')[1])
        .toList();
    
    return _courses.where((c) => favoriteCourseIds.contains(c.id)).toList();
  }

  /// 获取用户报名的课程
  Future<List<Course>> getUserEnrolledCourses(String userId) async {
    await Future.delayed(const Duration(milliseconds: 300));
    final enrolledCourseIds = _userEnrollments
        .where((key) => key.startsWith('${userId}_'))
        .map((key) => key.split('_')[1])
        .toList();
    
    return _courses.where((c) => enrolledCourseIds.contains(c.id)).toList();
  }

  /// 获取所有讲师
  Future<List<Instructor>> getAllInstructors() async {
    await Future.delayed(const Duration(milliseconds: 300));
    return List.from(_instructors);
  }

  /// 根据ID获取讲师详情
  Future<Instructor?> getInstructorById(String id) async {
    await Future.delayed(const Duration(milliseconds: 200));
    try {
      return _instructors.firstWhere((i) => i.id == id);
    } catch (e) {
      return null;
    }
  }

  /// 获取讲师的课程
  Future<List<Course>> getCoursesByInstructor(String instructorId) async {
    await Future.delayed(const Duration(milliseconds: 300));
    return _courses.where((c) => c.instructor.id == instructorId).toList();
  }

  /// 获取课程统计信息
  Future<Map<String, int>> getCourseStats() async {
    await Future.delayed(const Duration(milliseconds: 200));
    return {
      'total': _courses.length,
      'enrolling': _courses.where((c) => c.status == CourseStatus.enrolling).length,
      'ongoing': _courses.where((c) => c.status == CourseStatus.ongoing).length,
      'upcoming': _courses.where((c) => c.status == CourseStatus.upcoming).length,
      'completed': _courses.where((c) => c.status == CourseStatus.completed).length,
      'featured': _courses.where((c) => c.isFeatured).length,
    };
  }

  /// 获取课程类型统计
  Future<Map<String, int>> getTypeStats() async {
    await Future.delayed(const Duration(milliseconds: 200));
    final Map<String, int> stats = {};
    for (final course in _courses) {
      final typeText = course.typeText;
      stats[typeText] = (stats[typeText] ?? 0) + 1;
    }
    return stats;
  }

  /// 获取难度统计
  Future<Map<String, int>> getDifficultyStats() async {
    await Future.delayed(const Duration(milliseconds: 200));
    final Map<String, int> stats = {};
    for (final course in _courses) {
      final difficultyText = course.difficultyText;
      stats[difficultyText] = (stats[difficultyText] ?? 0) + 1;
    }
    return stats;
  }

  /// 清除所有数据（用于测试）
  void clearAllData() {
    _courses.clear();
    _userEnrollments.clear();
    _userFavorites.clear();
    _userProgress.clear();
    _instructors.clear();
  }
}